using System;
using System.Web;

namespace Jaws.Core.Web
{
    public class SslRedirection : IHttpModule
    {
        #region Implementation of IHttpModule

        /// <summary>
        /// Initializes a module and prepares it to handle requests.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpApplication" /> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application </param>
        public void Init(HttpApplication context)
        {
            context.BeginRequest += CheckIfUrlIsSecured;
            context.EndRequest += CheckIfUrlIsSecured;
        }

        /// <summary>
        /// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule" />.
        /// </summary>
        public void Dispose()
        {
            // Nothing to dispose
        }

        /// <summary>
        /// This will take the incoming request and make sure that it points to a secure URL.
        /// </summary>
        private static void CheckIfUrlIsSecured(object sender, EventArgs e)
        {
            HttpContext context = ((HttpApplication) sender).Context;
            string HttpUrl = context.Request.Url.ToString();

            if (HttpUrl.StartsWith("http:"))
            {
                HttpUrl = HttpUrl.Replace("http:", "https:");
                context.Response.Redirect(HttpUrl, true);
                context.Response.End();
            }
        }

        #endregion
    }
}